package com.aurora.source.util;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;

import com.aurora.source.R;
import com.aurora.source.util.netutil.DownloadUtil;

import java.io.File;
import java.util.List;

/**
 * Created by Lance on 2017/11/09
 */
public class UpdaterUtils {

    public static void startInstall(Context context, File file) {
        try {
            Uri fileUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                fileUri = FileProvider.getUriForFile(context, context.getPackageName(), file);
            } else {
                fileUri = Uri.fromFile(file);
            }
            Intent installIntent = new Intent(Intent.ACTION_VIEW);
            installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            installIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            installIntent.setAction(Intent.ACTION_VIEW);
            installIntent.setDataAndType(fileUri, "application/vnd.android.package-archive");
            context.startActivity(installIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 下载的apk和当前程序版本比较
     *
     * @param context Context 当前运行程序的Context
     * @param path    apk file's location
     * @return 如果当前应用版本小于apk的版本则返回true
     */
    public static boolean compare(Context context, String path) {
        PackageInfo apkInfo = getApkInfo(context, path);
        if (apkInfo == null) {
            return false;
        }

        String localPackage = context.getPackageName();
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(localPackage, 0);
            if (apkInfo.packageName.equals(localPackage)) {
                if (apkInfo.versionCode > packageInfo.versionCode) {
                    return true;
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 获取apk程序信息[packageName,versionName...]
     *
     * @param context Context
     * @param path    apk path
     */
    private static PackageInfo getApkInfo(Context context, String path) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
            if (info != null) {
                return info;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 要启动的intent是否可用
     *
     * @return boolean
     */
    public static boolean intentAvailable(Context context, Intent intent) {
        List list = null;
        try {
            PackageManager packageManager = context.getPackageManager();
            list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list.size() > 0;
    }


    /**
     * 系统的下载组件是否可用
     *
     * @return boolean
     */
    public static boolean checkDownloadState(Context context) {
        try {
            int state = context.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    public static void showDownloadSetting(Context context) {
        String packageName = "com.android.providers.downloads";
        Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + packageName));
        if (UpdaterUtils.intentAvailable(context, intent)) {
            context.startActivity(intent);
        }
    }

    /**
     * 获取下载状态
     *
     * @param downloadId an ID for the download, unique across the system.
     *                   This ID is used to make future calls related to this download.
     * @return int
     * @see DownloadManager#STATUS_PENDING
     * @see DownloadManager#STATUS_PAUSED
     * @see DownloadManager#STATUS_RUNNING
     * @see DownloadManager#STATUS_SUCCESSFUL
     * @see DownloadManager#STATUS_FAILED
     */
    public static int getDownloadStatus(DownloadManager downloadManager, long downloadId) {
        try {
            DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
            Cursor c = downloadManager.query(query);
            if (c != null) {
                try {
                    if (c.moveToFirst()) {
                        return c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
                    }
                } finally {
                    c.close();
                }
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return -1;
    }

    // 下载apk 先判断是否存在
    public static void downloadApkFile(final Activity activity, final String url, final ProgressDialog progressDialog,
                                       final AlertDialog.Builder builder, final String title, final boolean isOnLogin) {

        String apkDownload = activity.getExternalFilesDir("apk").getAbsolutePath();

        File currentFile = new File(apkDownload + "/source.apk");
        if (currentFile.exists()) {
            if (UpdaterUtils.compare(activity, apkDownload + "/source.apk")) {
                ToastUtils.showTextLong(activity, "发现最新版本安装包,可直接安装");
                // 自动更新   8.0 安装 apk 注意
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    boolean b = activity.getPackageManager().canRequestPackageInstalls();
                    if (b) {
                        startInstall(activity, currentFile);
                    } else {
                        // 请求安装未知应用来源的权限
                        activity.requestPermissions(new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, 0);
                        startInstall(activity, currentFile);
                    }
                } else {
                    startInstall(activity, currentFile);
                }
            } else {
                if (currentFile.delete()) {
                    showUpdateDialog(activity, url, apkDownload, progressDialog, builder, title, isOnLogin);// 下载 Apk
                }
            }
        } else {
            showUpdateDialog(activity, url, apkDownload, progressDialog, builder, title, isOnLogin);// 下载 Apk
        }
    }

    // 更新弹窗 确认是否下载apk
    private static void showUpdateDialog(final Activity activity, final String url, final String apkDownload, final ProgressDialog progressDialog,
                                         final AlertDialog.Builder builder, final String title, final boolean isOnLogin) {
        try {
            if (NetworkUtils.isAvailable(activity)) {
                if (NetworkUtils.isWifiConnected(activity)) {
                    builder.setTitle(title)//设置对话框标题
                            .setMessage("当前处于wifi状态下,是否更新")//设置显示的内容
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                                @Override
                                public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                    downloadFile(activity, url, apkDownload, progressDialog);
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮

                        @Override
                        public void onClick(DialogInterface dialog, int which) {//响应事件
                            if (isOnLogin) {
                                forceUpdate(activity, url, apkDownload, progressDialog, builder, title, isOnLogin);// 强制更新
                            }
                        }

                    }).setCancelable(false)
                            .show();
                } else {
                    builder.setTitle(title)//设置对话框标题
                            .setMessage("当前处于移动网络状态下,是否更新")//设置显示的内容
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                                @Override
                                public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                    downloadFile(activity, url, apkDownload, progressDialog);
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {//响应事件
                            if (isOnLogin) {
                                forceUpdate(activity, url, apkDownload, progressDialog, builder, title, isOnLogin);// 强制更新
                            }
                        }
                    }).setCancelable(false)
                            .show();
                }
            } else {
                ToastUtils.showTextShort(activity, "请打开网络!");
                NetworkUtils.openWirelessSettings(activity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 强制更新
    private static void forceUpdate(final Activity activity, final String url, final String apkDownload, final ProgressDialog progressDialog,
                                    final AlertDialog.Builder builder, final String title, final boolean isOnLogin) {
        ToastUtils.showTextLong(activity, "本次更新为强制更新,更新后才可使用");
        showUpdateDialog(activity, url, apkDownload, progressDialog, builder, title, isOnLogin);// 下载 Apk
    }

    // 下载apk
    private static void downloadFile(final Activity activity, String url, String apkDownload, final ProgressDialog progressDialog) {
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setIcon(R.mipmap.ic_launcher_foreground);
        progressDialog.setTitle("溯源系统自动更新");
        progressDialog.setMessage("亲，努力下载中...");
        progressDialog.setProgress(0);
        progressDialog.setMax(100);
        progressDialog.show();
        progressDialog.setCancelable(false);

        DownloadUtil.get().download(url, apkDownload, "source.apk", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                //下载完成进行相关逻辑操作
                if (file.exists()) {
                    startInstall(activity, file);
                } else {
                    ToastUtils.showTextShort(activity, "安装包不存在,本次更新失败,请重新下载");
                }
            }

            @Override
            public void onDownloading(int progress) {
                progressDialog.setProgress(progress);
            }

            @Override
            public void onDownloadFailed(Exception e) {
                //下载异常进行相关提示操作
            }
        });
    }

}


